<template>
  <div>
    <div class="page-header">
      <div class="page-header-index-wide">
        <div style="overflow: hidden">
          <!-- <a style="margin-right: 20px; margin-bottom: 15px; float: left;"><router-link to="/landCenter/orderDispatch?f=1"><a-icon type="left" />返回</router-link></a> -->
          <a-breadcrumb style="margin-bottom: 15px; float: left;">
            <a-breadcrumb-item>
              <router-link to="/landCenter/orderDispatch">订单调度</router-link>
            </a-breadcrumb-item>
            <a-breadcrumb-item>订单详情</a-breadcrumb-item>
          </a-breadcrumb>
        </div>

        <div class="detail">
          <div class="main">
            <div class="row" style=" margin-bottom:8px;">
              <img src="/static/images/driver.png" class="logo" />
              <div class="title">
                <div>
                  <h1>
                    公司编号：{{detail.truckOrderCode}}
                    <a-tag
                      v-if="!isLandCenterOrder"
                      color="orange"
                      style="vertical-align: text-top;"
                    >佳华业务</a-tag>
                    <a-tag
                      v-if="isLandCenterOrder"
                      color="orange"
                      style="vertical-align: text-top;"
                    >佳特业务</a-tag>
                    <a-tag
                      v-if="detail.isUrgent===1"
                      color="red"
                      style="vertical-align: text-top;"
                    >加急</a-tag>
                  </h1>
                </div>
              </div>
              <div class="action">
                <orderOperate type="detail" :item="detail" @initPage="initDetail">
                  <a-dropdown v-if="detail.status === 6">
                    <a-menu slot="overlay" @click="handleMenuClick" style="text-align: center;">
                      <a-menu-item :key="1">费用已录完</a-menu-item>
                      <a-menu-item :key="0">费用未录完</a-menu-item>
                    </a-menu>
                    <a-button>
                      {{billStatusStr}}
                      <a-icon type="down" />
                    </a-button>
                  </a-dropdown>
                  <a-button
                    type="primary"
                    v-if="isAssignDriver(detail)"
                    @click="doAssign('ASSIGN', detail.status, detail.orderTruckId, 1, (detail.containerNo&&detail.containerSealNo) ? 2 : 1)"
                    style="margin-left: 10px;"
                  >指派</a-button>
                  <a-button
                    type="primary"
                    v-if="isChangeDriver(detail)"
                    @click="doAssign('RE_ASSIGN', detail.status, detail.orderTruckId, detail.dispatchType, (detail.containerNo&&detail.containerSealNo) ? 2 : 1)"
                    style="margin-left: 10px;"
                  >改派</a-button>
                </orderOperate>
              </div>
            </div>
            <div class="row">
              <div class="headerContent">
                <detail-list size="small" :col="3" class="detail-layout">
                  <detail-list-item term="运单号">{{detail.seagoingShipOrderCode||'--'}}</detail-list-item>
                  <detail-list-item term="海船公司">{{detail.seagoingShipCompanyName||'--'}}</detail-list-item>
                  <detail-list-item
                    term="起运/目的港"
                  >{{detail.startPortName||'--'}} — {{detail.endPortName||'--'}}</detail-list-item>
                </detail-list>
                <detail-list size="small" :col="3" class="detail-layout">
                  <detail-list-item term="订单类型">{{orderTypeStr(detail.orderType)}}</detail-list-item>
                  <detail-list-item term="客户名称">{{detail.custName||'--'}}</detail-list-item>
                  <detail-list-item term="运输条款">{{detail.transportTerms||'--'}}</detail-list-item>
                </detail-list>
                <detail-list size="small" :col="3" class="detail-layout">
                  <detail-list-item
                    term="驳船船名航次"
                  >{{detail.shipName||'--'}}/{{detail.shipVoyage||'--'}}</detail-list-item>
                  <detail-list-item
                    term="海船船名航次"
                  >{{detail.seagoingShipName||'--'}}/{{detail.seagoingShipVoyage||'--'}}</detail-list-item>
                </detail-list>
                <detail-list size="small" :col="3" class="detail-layout">
                  <detail-list-item term="所属销售">{{detail.sellerName||'--'}}</detail-list-item>
                  <detail-list-item term="所属操作">{{detail.handlerName||'--'}}</detail-list-item>
                </detail-list>
              </div>
              <div class="extra">
                <a-row class="status-list">
                  <a-col :span="24">
                    <div class="text">状态</div>
                    <div class="heading">
                      {{statusStr}}
                      <!-- 作废原因 -->
                      <a-tooltip
                        v-if="detail.status===8&&detail.isAnomalous===1"
                        placement="topLeft"
                      >
                        <template slot="title">
                          <span>{{detail.anomalousReason}}</span>
                        </template>
                        <a-icon type="info-circle" theme="twoTone" />
                      </a-tooltip>
                    </div>
                    <!-- 佳华异常结束 -->
                    <div v-if="detail.isShipAnomalous===1" class="text">
                      订单已被佳华异常结束
                      <a-tooltip placement="bottomLeft">
                        <template slot="title">
                          <span>{{detail.shipAbnormalReason}}</span>
                        </template>
                        <a-icon type="info-circle" theme="twoTone" style="font-size: 13px;" />
                      </a-tooltip>
                      <br />
                      （{{detail.shipCompleteTime}}）
                    </div>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="page-menu-tabs">
        <a-tabs :tabBarStyle="{}" @change="onChangeTab">
          <a-tab-pane tab="装卸详情" key="1">
            <div class="content">
              <div class="page-header-index-wide">
                <!-- 装卸信息 -->
                <a-card :bordered="false">
                  <a-form-model
                    ref="form"
                    :model="form"
                    :rules="rules"
                    :labelCol="{span: 6}"
                    :wrapperCol="{span: 16}"
                  >
                    <template v-if="baseEditable || completedOrder">
                      <a-button
                        v-if="!editpart.flag"
                        class="cardCancel"
                        @click="editpartHandle(true)"
                      >取消</a-button>
                      <a-button
                        type="primary"
                        class="cardEdit"
                        @click="editpartHandle(false)"
                      >{{editpart.text}}</a-button>
                    </template>
                    <div class="card-title">装卸信息</div>
                    <a-row class="detail1">
                      <a-col :span="8">
                        <a-form-model-item label="货品名称">
                          <span>{{detail.goodsName || '--'}}</span>
                        </a-form-model-item>
                        <a-form-model-item label="箱型箱量">
                          <span>{{detail.containerType}}*{{detail.containerNum||1}}</span>
                        </a-form-model-item>
                        <!-- 进口订单（佳华订单）：箱号、封号不可进行编辑 -->
                        <a-form-model-item label="箱  号" prop="containerNoAndName">
                          <!-- 佳华进口不可编辑 -->
                          <span
                            v-if="(!isLandCenterOrder && isImportOrder) || editpart.flag"
                          >{{getSealNoAndNameString(detail.containerNo, detail.holderName) || '--'}}</span>
                          <!-- 佳特，格式输入 -->
                          <a-popover
                            v-if="isLandCenterOrder && !editpart.flag"
                            trigger="click"
                            :visible="clicked"
                            placement="right"
                          >
                            <div slot="content">
                              <a-form-model ref="formSave" :rules="rulesSave" :model="formSave">
                                <a-form-model-item
                                  label="箱号"
                                  prop="a"
                                  :labelCol="{span:7}"
                                  :wrapperCol="{span:15}"
                                >
                                  <a-input v-model="formSave.a" @change="changeA"></a-input>
                                </a-form-model-item>
                                <a-form-model-item
                                  label="持箱人"
                                  prop="b"
                                  :labelCol="{span:7}"
                                  :wrapperCol="{span:15}"
                                >
                                  <a-input v-model="formSave.b"></a-input>
                                </a-form-model-item>
                              </a-form-model>
                              <div style="width: 100px; margin: 0 auto;">
                                <a-button type="link" @click="cancelSave">取消</a-button>
                                <a @click="save">保存</a>
                              </div>
                            </div>
                            <a-button
                              @click="openSave"
                              style="min-width: 180px;text-align: left;"
                            >{{sealNoAndNameDisplayId}}</a-button>
                          </a-popover>
                          <!-- 佳华非进口 下拉选择 -->
                          <template v-if="!isLandCenterOrder && !isImportOrder  && !editpart.flag">
                            <a-select
                              style="width: 70%;"
                              show-search
                              v-model="sealNoAndNameDisplayId"
                              :show-arrow="false"
                              :filter-option="false"
                              :default-active-first-option="false"
                              :not-found-content="null"
                              @search="handleNameChange"
                              @select="handleNameSelect"
                            >
                              <a-select-option
                                v-for="d in sealNoAndNameList"
                                :key="d.containerFlowId"
                              >{{getSealNoAndNameString(d.containerNo, d.holderName) || '--'}}</a-select-option>
                            </a-select>
                            <a-popover trigger="click" :visible="clicked" placement="right">
                              <div slot="content">
                                <a-form-model ref="formSave" :rules="rulesSave" :model="formSave">
                                  <a-form-model-item
                                    label="箱号"
                                    prop="a"
                                    :labelCol="{span:7}"
                                    :wrapperCol="{span:15}"
                                  >
                                    <a-input v-model="formSave.a" @change="changeA"></a-input>
                                  </a-form-model-item>
                                  <a-form-model-item
                                    label="持箱人"
                                    prop="b"
                                    :labelCol="{span:7}"
                                    :wrapperCol="{span:15}"
                                  >
                                    <a-input v-model="formSave.b"></a-input>
                                  </a-form-model-item>
                                </a-form-model>
                                <div style="width: 100px; margin: 0 auto;">
                                  <a-button type="link" @click="cancelSave">取消</a-button>
                                  <a @click="save">保存</a>
                                </div>
                              </div>
                              <a @click="openSave" style="margin-left: 6px;">其他箱号</a>
                            </a-popover>
                            <p
                              style="color: red; margin: 0; height: 20px;line-height: 20px;"
                            >选不到箱号？请点击其他箱号</p>
                          </template>
                        </a-form-model-item>
                        <a-form-model-item label="封  号">
                          <template v-if="(!isLandCenterOrder && isImportOrder) || editpart.flag">
                            <span style="margin-right: 5px;">{{detail.containerSealNo || '--'}}</span>
                            <a-tooltip
                              placement="bottom"
                              :title="detail.sealNoUpdateReason||'暂无原因'"
                            >
                              <a-icon type="info-circle" style="color: #1890ff" />
                            </a-tooltip>
                          </template>
                          <template v-if="(isLandCenterOrder || !isImportOrder) && !editpart.flag">
                            <input
                              type="text"
                              :value="form.containerSealNo"
                              readonly
                              @click="changeContainerSealNo"
                              class="inputReadonly"
                            />
                            <a-tooltip placement="bottom" :title="form.sealNoUpdateReason||'暂无原因'">
                              <a-icon type="info-circle" style="color: #1890ff" />
                            </a-tooltip>
                          </template>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-model-item label="要求送达" prop="requiredArriveTime">
                          <span
                            v-if="editpart.flag || completedOrder"
                          >{{detail.requiredArriveTime || '--'}}</span>
                          <a-date-picker
                            :show-time="{format:'HH:mm'}"
                            format="YYYY-MM-DD HH:mm"
                            v-if="!editpart.flag && !completedOrder"
                            :value="requiredArriveTimeObj"
                            @change="onChangeDate"
                            style="width: 100%"
                          ></a-date-picker>
                        </a-form-model-item>
                        <!-- 佳华订单，货重字段不可编辑 -->
                        <a-form-model-item label="货重（吨）">
                          <span
                            v-if="!isLandCenterOrder || editpart.flag || completedOrder"
                          >{{detail.goodsWeight || '--'}}</span>
                          <a-input-number
                            v-if="isLandCenterOrder && !editpart.flag && !completedOrder"
                            :min="0"
                            :precision="2"
                            :max="999999999999.99"
                            v-model="form.goodsWeight"
                            style="width: 100%"
                          ></a-input-number>
                        </a-form-model-item>
                        <a-form-model-item label="操作备注">
                          <span class="formText">{{detail.handlerRemark || '--'}}</span>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-model-item label="调度备注">
                          <span
                            v-if="editpart.flag || completedOrder"
                          >{{detail.dispatcherRemark || '--'}}</span>
                          <a-textarea
                            v-if="!editpart.flag && !completedOrder"
                            v-model="form.dispatcherRemark"
                            :rows="4"
                            :max-length="200"
                          ></a-textarea>
                        </a-form-model-item>
                      </a-col>
                    </a-row>
                  </a-form-model>
                </a-card>

                <!-- 1.1.1运输信息 -->
                <a-card :bordered="false" v-if="detail.belongCompany==='JIA_HUA'">
                  <div class="card-title hasContent">运输信息</div>
                  <a-form-model :labelCol="{span: 10}" :wrapperCol="{span: 14}">
                    <a-row v-if="isExportOrder">
                      <a-col :span="8">
                        <a-form-model-item label="目的港">
                          <span>{{detail.endPortName || '--'}}</span>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-model-item label="收货地址/收货人抬头">
                          <span>{{detail.consigneeProvince || '--'}}{{detail.consigneeCity}}{{detail.consigneeArea}} {{detail.consigneeAddress}}</span>
                          <br />
                          <span>{{detail.consigneeTitle}}</span>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="8">
                        <a-form-model-item label="收货人">
                          <span>{{detail.consignee || '--'}} {{detail.consigneePhone}}</span>
                        </a-form-model-item>
                      </a-col>
                    </a-row>
                    <a-row v-if="isImportOrder">
                      <a-col :span="7">
                        <a-form-model-item label="起运港">
                          <span>{{detail.startPortName || '--'}}</span>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="10">
                        <a-form-model-item label="发货地址">
                          <span>{{detail.consignorProvince || '--'}}{{detail.consignorCity}}{{detail.consignorArea}} {{detail.consignorAddress}}</span>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="7">
                        <a-form-model-item label="发货人">
                          <span>{{detail.consignor || '--'}} {{detail.consignorPhone}}</span>
                        </a-form-model-item>
                      </a-col>
                    </a-row>
                  </a-form-model>
                </a-card>

                <!-- 装卸地址 -->
                <a-card :bordered="false">
                  <div class="card-title hasContent">
                    装卸地址
                    <a-button
                      v-if="baseEditable && tableData.length < 3"
                      type="primary"
                      @click="loadingGate"
                      style="float: right;"
                    >新增门点</a-button>
                  </div>
                  <a-row>
                    <a-col :span="24">
                      <a-table
                        :columns="columns"
                        :data-source="tableData"
                        :pagination="false"
                        :loading="loading"
                        size="small"
                        rowKey="addressId"
                      >
                        <template v-if="baseEditable" slot="opt" slot-scope="text, record, index">
                          <a @click="editIt(index)">编辑</a>
                          <a v-if="record.isDeleteable === 1" @click="deleteIt(index)">删除</a>
                        </template>
                      </a-table>
                    </a-col>
                  </a-row>
                </a-card>

                <!-- 派单信息 -->
                <a-card :bordered="false">
                  <div class="card-title hasContent">
                    派单信息
                    <div v-if="detail.status !== 8" style="float: right;">
                      <a-button
                        type="primary"
                        v-if="isAssignDriver(detail)"
                        @click="doAssign('ASSIGN', detail.status, detail.orderTruckId, 1, (detail.containerNo&&detail.containerSealNo) ? 2 : 1)"
                        style="margin-left: 10px;"
                      >派单</a-button>
                      <a-button
                        type="primary"
                        v-if="isChangeDriver(detail)"
                        @click="doAssign('RE_ASSIGN', detail.status, detail.orderTruckId, detail.dispatchType, (detail.containerNo&&detail.containerSealNo) ? 2 : 1)"
                        style="margin-left: 10px;"
                      >改派</a-button>
                      <!-- 司机待接单(指定N个司机) -->
                      <a-button
                        type="primary"
                        v-if="detail.status === 3 && detail.dispatchCount > 1"
                        @click="doAssign('ASSIGN', detail.status, detail.orderTruckId, 1, (detail.containerNo&&detail.containerSealNo) ? 2 : 1)"
                        style="margin-left: 10px;"
                      >指派详情</a-button>
                    </div>
                  </div>
                  <detail-list size="small" :col="4" class="detail-layout">
                    <detail-list-item term="离港形式">{{dispatchTypeStr}}</detail-list-item>
                    <detail-list-item term="提箱类型">{{dispatchEmptyOrHeavyStr}}</detail-list-item>
                    <detail-list-item term="司机">
                      {{driverStr}}
                      <a-tag v-if="detail.isSelfOperation===1" color="green">自营</a-tag>
                      <a-tag v-if="detail.isSelfOperation===0" color="green">外派</a-tag>
                    </detail-list-item>
                    <detail-list-item term="车辆">
                      {{detail.tractorNumber || '--'}}{{detail.trailerNumber ? `·${detail.trailerNumber}` : ''}}
                      <a-tag v-if="detail.isSelfOperation===1" color="green">自营</a-tag>
                      <a-tag v-if="detail.isSelfOperation===0" color="green">外派</a-tag>
                    </detail-list-item>
                  </detail-list>
                </a-card>
              </div>
            </div>
          </a-tab-pane>

          <a-tab-pane tab="流程跟踪" key="2">
            <a-card :bordered="false">
              <a-row>
                <a-col :span="6">
                  <div class="card-title">流程跟踪</div>
                  <div class="leftFlowList">
                    <a-timeline>
                      <a-timeline-item v-for="v in truckFlowList" :key="v.flowId">
                        <div
                          :class="{errorClass: v.opeType===20||v.opeType===21}"
                          style="padding: 0 5px;"
                        >
                          {{opeTypeStr(v.opeType, v.emptyOrHeavy)}}
                          <br />
                          <span style="color: #b7b7b7">{{v.createTime}}</span>
                          <br />

                          <!-- 异常结束的类型需要显示异常结束的原因 -->
                          <small v-if="v.opeType===4">
                            原因：{{v.remark}}
                            <br />
                          </small>
                          <!-- 作废 -->
                          <small v-if="v.opeType===5">
                            原因：{{v.remark}}
                            <br />
                          </small>
                          <!-- 套箱接单的类型需要显示备注信息 -->
                          <small v-if="v.opeType===20">
                            {{v.remark}}
                            <br />
                          </small>
                          <!-- 送达门点 提箱、不提箱-->
                          <small v-if="v.address&&v.address.addressType===1&&v.type===12">
                            {{v.address.portName}}
                            <br />
                          </small>
                          <small v-if="v.address&&v.address.addressType===2&&v.type===12">
                            {{`${v.address.province}${v.address.city}${v.address.area}${v.address.address}`}}
                            <br />
                          </small>
                          <small v-if="v.type===12">
                            {{`${v.driverName ? v.address.linkMan : '--'} ${v.address ? v.address.linkManPhone : '--'}`}}
                            <br />
                          </small>
                          <small v-if="v.opeType===10">
                            司机：{{`${v.driverName || '--'} ${v.driverPhone || '--'}`}}
                            <br />
                            车辆：{{v.tractorNumber || '--'}}{{v.trailerNumber ? `·${v.trailerNumber}` : ''}}
                          </small>

                          <a
                            v-if="v.opeType===11||v.type===12||v.opeType===13||v.opeType===14||v.opeType===16||v.opeType===17||v.opeType===22||v.opeType===21||v.opeType===18"
                            @click="openFlowDetail(v)"
                          >查看详情</a>
                        </div>
                      </a-timeline-item>
                    </a-timeline>
                  </div>
                </a-col>
                <a-col :span="18">
                  <a-col :span="10" style="padding-left:2%;">
                    {{detail.tractorNumber}}{{detail.trailerNumber ? `·${detail.trailerNumber}` : ''}}
                    <span
                      v-if="detail.isSelfOperation===1"
                      class="selfFlag"
                    >自</span>
                  </a-col>
                  <a-col :span="10">
                    {{detail.driverName}}{{detail.driverPhone ? `·${detail.driverPhone}` : ''}}
                    <span
                      v-if="detail.driverIsSelfOperation===1"
                      class="selfFlag"
                    >自</span>
                  </a-col>

                  <template
                    v-if="detail.isSelfOperation!==1 || (detail.status!==4&&detail.status!==5)"
                  >
                    <a-col :span="24" class="mapLoc">
                      <a-empty description="暂无跟踪数据" />
                    </a-col>
                  </template>

                  <template
                    v-if="detail.isSelfOperation===1 && (detail.status===4||detail.status===5)"
                  >
                    <a-col :span="24" class="mapLoc">
                      <trackInfo :id="detail.orderTruckId" :type="1" />
                    </a-col>
                  </template>
                </a-col>
              </a-row>
            </a-card>
          </a-tab-pane>

          <a-tab-pane tab="费用明细" key="3">
            <a-card
              v-if="showOilDetail && (detail.status === 6 || detail.status === 7 || detail.status === 8)"
              :bordered="false"
            >
              <div class="card-title">行程费用</div>
              <a-table :columns="columns0" :dataSource="[{id: 2}]" :pagination="false" rowKey="id">
                <template slot="k1">
                  <a-input-number
                    :disabled="isOilOut"
                    :min="0"
                    :precision="2"
                    :step="0.01"
                    :max="999999999999.99"
                    v-model="k1"
                    @change="onChangeMileage"
                    @blur="saveOilData"
                  ></a-input-number>
                </template>
                <template slot="k2">
                  <a-select
                    v-model="k2"
                    :disabled="isOilOut"
                    @change="onChangeRate"
                    class="selectWidth"
                  >
                    <a-select-option
                      key="1"
                      :value="detail.singleOilConsumption"
                    >单重：{{detail.singleOilConsumption}}</a-select-option>
                    <a-select-option
                      key="2"
                      :value="detail.doubleOilConsumption"
                    >双重：{{detail.doubleOilConsumption}}</a-select-option>
                    <a-select-option
                      key="3"
                      :value="detail.emptyOilConsumption"
                    >空车：{{detail.emptyOilConsumption}}</a-select-option>
                  </a-select>
                </template>
                <template slot="k3">
                  <a-input-number
                    :disabled="isOilOut"
                    v-model="k3"
                    @change="onChangeOilVolume"
                    @blur="saveOilData"
                    :min="0"
                    :precision="2"
                    :step="0.01"
                    :max="999999999999.99"
                  ></a-input-number>
                </template>
                <template slot="k4">
                  ￥ {{oilDetail.totalAmount}}&nbsp;
                  <a-button v-if="!isOilOut" type="primary" @click="sureOil">确定</a-button>&nbsp;
                  <a v-if="isOilOut" @click="viewDetail">查看明细</a>
                  <a v-if="!isOilOut" @click="viewDetailLocal">查看明细</a>
                </template>
              </a-table>
            </a-card>
            <a-card :bordered="false">
              <div class="card-title">
                应收费用
                <a-button
                  v-if="detail.status !== 8"
                  type="primary"
                  @click="addFee(1)"
                  style="float: right"
                >+ 增加应收</a-button>
              </div>
              <a-table
                :columns="columns1"
                :dataSource="feeTypeList1"
                rowKey="id"
                :pagination="false"
              >
                <template slot="opt" slot-scope="text, record">
                  <a @click="viewHistory(record.id)">历史记录</a>
                  <a-button
                    v-if="record.status!==2&&record.status!==3&&record.custId!==3"
                    type="link"
                    @click="editbill(record, 1)"
                  >编辑</a-button>
                </template>
              </a-table>
              <div style="float: right; margin-top: 10px">
                <h3>应收总金额：¥ {{data1}}</h3>
              </div>
            </a-card>
            <a-card :bordered="false">
              <div class="card-title">
                应付费用
                <a-button
                  v-if="detail.status !== 8"
                  type="primary"
                  @click="addFee(2)"
                  style="float: right"
                >+ 增加应付</a-button>
              </div>
              <a-table
                :columns="columns2"
                :dataSource="feeTypeList2"
                rowKey="id"
                :pagination="false"
              >
                <template slot="opt" slot-scope="text, record">
                  <a @click="viewHistory(record.id)">历史记录</a>
                  <a-button
                    v-if="record.status!==2&&record.status!==3&&record.custId!==3"
                    type="link"
                    @click="editbill(record, 2)"
                  >编辑</a-button>
                </template>
              </a-table>
              <div style="float: right; margin-top: 10px">
                <h3>应付总金额：¥ {{data2}}</h3>
              </div>
            </a-card>
            <a-card :bordered="false">
              <div class="card-title">毛利</div>
              <a-table
                :columns="columns4"
                :dataSource="[{id: 1, a: `¥ ${data1}`, b: `¥ ${data2}`, c: `¥ ${Math.round((data1 - data2) * 100) / 100}`}]"
                rowKey="id"
                :pagination="false"
              ></a-table>
            </a-card>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>

    <!-- 修改封号 -->
    <a-modal
      :visible="sealNoVisible"
      title="修改封号"
      centered
      destroyOnClose
      :maskClosable="false"
      @ok="setSealNoData"
      @cancel="changeSealNoCancel"
    >
      <a-form-model :labelCol="{span: 6}" :wrapperCol="{span: 16}">
        <a-form-model-item label="封号">
          <a-input v-model="containerSealNo" :max-length="15"></a-input>
        </a-form-model-item>
        <a-form-model-item label="原因">
          <a-textarea :rows="3" v-model="sealNoUpdateReason" placeholder="请输入修改封号的原因"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 门点modal -->
    <loadAndUnloadModal :visible="loadingVisible" :data="loadingGateData" @closeIt="loadingClose" />
    <!-- 流转modal -->
    <flowDetail :visible="flowVisible" :flow="flow" @closeIt="dealFlowModal" />
    <!-- 新增应收应付 -->
    <a-modal
      :visible="addVisible"
      :title="!tempRecord.feetypeId ? `新增应${currentAddTypeStr}` : `编辑应${currentAddTypeStr}`"
      centered
      destroyOnClose
      :maskClosable="false"
      :confirmLoading="addConfirmLoading"
      @ok="saveAddFee"
      @cancel="cancelAddFee"
    >
      <a-form-model
        ref="feeForm"
        :model="feeForm"
        :rules="feeRules"
        :labelCol="{span: 6}"
        :wrapperCol="{span: 16}"
      >
        <a-form-model-item label="选择费用类型" prop="feetypeId">
          <a-select v-model="feeForm.feetypeId" @change="onchangeFeeType" :disabled="disabledCust0">
            <a-select-option value>请选择</a-select-option>
            <a-select-option v-for="(v,k) in feeList" :key="k" :value="v.id">{{v.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选择结算对象" prop="custId">
          <a-select
            v-if="!disabledCust"
            show-search
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            v-model="feeForm.custId"
            @search="handleCustNameChange"
            @select="emptyChange"
          >
            <a-select-option value>请选择</a-select-option>
            <a-select-option v-for="d in custIdList" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
          <span v-if="disabledCust">{{detail.custName}}</span>
        </a-form-model-item>
        <a-form-model-item :label="`应${currentAddTypeStr}金额`" prop="amount">
          <a-input-group compact>
            <a-input-number style="width: 70%" v-model="feeForm.amount" :precision="2" :min="0"></a-input-number>
            <a-select style="width: 30%" v-model="feeForm.currencyType">
              <a-select-option v-for="v in moneyTypeArray" :key="v">{{v}}</a-select-option>
              <!-- <a-select-option key="CNY">CNY</a-select-option>
              <a-select-option key="USD">USD</a-select-option>-->
            </a-select>
          </a-input-group>
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea v-model="feeForm.remark"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 油耗费用明细 -->
    <a-modal
      width="650px"
      :visible="detailVisible"
      title="油耗费用明细"
      centered
      destroyOnClose
      :maskClosable="false"
      @cancel="cancelDetail"
      :footer="null"
    >
      <a-row>
        <a-col :span="24">
          <a-table
            size="small"
            :columns="columns3"
            :data-source="oilDetail.purchaseList"
            :pagination="false"
            :row-key="(record,index) => index"
          ></a-table>
        </a-col>
      </a-row>
    </a-modal>

    <!-- 派 -->
    <assign
      :visible="assignModal.visible"
      :type="assignModal.type"
      :order="assignModal.order"
      @setAssignVisible="setAssignVisible"
    ></assign>

    <!-- 历史记录 -->
    <a-modal
      :visible="historyVisible"
      title="历史记录"
      @cancel="cancelSee"
      width="900px"
      :footer="null"
    >
      <a-table :columns="columnsLocal" :data-source="detailData" rowKey="id" :pagination="false"></a-table>
    </a-modal>
  </div>
</template>

<script>
import { Timeline } from 'ant-design-vue'
import moment from 'moment'
import debounce from 'lodash/debounce'
import assign from './assign'
import trackInfo from './track'
import { mixin } from './common'
import orderOperate from './orderOperations'
import loadAndUnloadModal from './loadAndUnloadModal'
import DetailList from '@/components/DescriptionList'
import flowDetail from './orderFlowDetailModal'
import { queryFeeTypeList, queryCustNameList } from '@/api'
import {
  queryTruckOrderDetail, updateOrderTruckInfo, queryReportContainerListPc, deleteOrderTruckAddress,
  queryOrderTruckFlowList, queryShipOrderCostList, addBillCost, queryOrderTruckOilDetail, updateOrderTruckCostRecorded,
  queryHistoryCostList, updateBillCost, queryContainerNoIsHaveOrder, updateOrderTruckOilVolumeNew, queryTruckOilInByOilVolume
} from '@/api/landCenter'
import { OrderOptions } from '../options'

const DetailListItem = DetailList.Item
const fomrMessage = `必填项不能为空`
const buttonDefault = { text: '编辑', flag: true }
const buttonEdit = { text: '保存', flag: false, saveLoading: false }
const statusArray = ['', '待接单', '待派单', '司机待接单', '司机待出发', '运输中', '已完成', '已结算', '已作废']
const defaultFeeForm = (feeType) => {
  return {
    feeType, // 应收应付：1应收、2应付
    custId: '', // 结算对象id
    feetypeId: '', // 费用id
    amount: '', // 金额
    currencyType: '请选择', // 币种
    remark: '' // 备注
  }
}

export default {
  props: ['id'],
  mixins: [mixin],
  components: {
    orderOperate,
    DetailList,
    DetailListItem,
    loadAndUnloadModal,
    [Timeline.name]: Timeline,
    [Timeline.Item.name]: Timeline.Item,
    flowDetail,
    assign,
    trackInfo
  },
  data () {
    this.handleNameChange = debounce(this.handleNameChange, 800)
    this.handleCustNameChange = debounce(this.handleCustNameChange, 800)

    const columns = [
      {
        title: '港口/门点地址',
        dataIndex: 'addressType',
        customRender: (text, record) => {
          if (text === 1) { // 港口
            let a = '港'
            if (this.detail.belongCompany === 'JIA_HUA') {
              a = this.isImportOrder ? '目的港' : (this.isExportOrder ? '起运港' : '港')
            }
            return <div>{record.portName} <span class='gangIcon'>{a}</span></div>
          } else {
            return `${record.province}${record.city}${record.area}${record.address}`
          }
        }
      },
      { title: '联系人', dataIndex: 'linkMan' },
      { title: '联系人电话号码', dataIndex: 'linkManPhone' },
      {
        title: '类型',
        dataIndex: 'opeType',
        customRender: (text, record) => {
          return text === 1 ? '装货' : (text === 2 ? '卸货' : (text === 3 ? '提箱' : '空车'))
        }
      },
      { title: '备注', dataIndex: 'remark', ellipsis: true },
      { title: '操作', scopedSlots: { customRender: 'opt' }, width: '100px' }
    ]

    const columns0 = [
      {
        title: '里程数(km)',
        scopedSlots: { customRender: 'k1' }
      },
      {
        title: '耗油系数(L/km)',
        scopedSlots: { customRender: 'k2' }
      },
      {
        title: '耗油量(L)',
        scopedSlots: { customRender: 'k3' }
      },
      {
        title: '油耗费用(元)',
        scopedSlots: { customRender: 'k4' }
      }
    ]
    const columns1 = [
      {
        title: '费用类型',
        dataIndex: 'feeName'
      },
      {
        title: '应收金额',
        dataIndex: 'amount',
        customRender: (text, record, index) => {
          if (record.currencyType === 'USD') return <span class="orange">${text}</span>
          else return text
        }
      },
      {
        title: '结算对象',
        dataIndex: 'custName'
      },
      {
        title: '备注',
        dataIndex: 'remark',
        customRender: (text, record, index) => {
          return <div>{record.createTime} {record.operator}<br />{text ? `备注：${text}` : ''}</div>
        }
      },
      { title: '操作', scopedSlots: { customRender: 'opt' }, width: '160px' }
    ]
    const columns2 = [
      {
        title: '费用类型',
        dataIndex: 'feeName'
      },
      {
        title: '应付金额',
        dataIndex: 'amount',
        customRender: (text, record, index) => {
          if (record.currencyType === 'USD') return <span class="orange">${text}</span>
          else return text
        }
      },
      {
        title: '结算对象',
        dataIndex: 'custName'
      },
      {
        title: '操作信息',
        dataIndex: 'operator'
      },
      {
        title: '备注',
        dataIndex: 'remark',
        customRender: (text, record, index) => {
          return <div>{record.createTime} {record.operator}<br />{text ? `备注：${text}` : ''}</div>
        }
      },
      { title: '操作', scopedSlots: { customRender: 'opt' }, width: '160px' }
    ]

    const columns3 = [
      {
        title: '采购批次',
        dataIndex: 'batchNo'
      }, {
        title: '单价(元/L)',
        dataIndex: 'price'
      }, {
        title: '油量(L)',
        dataIndex: 'oilVolume'
      }, {
        title: '交易金额(元)',
        dataIndex: 'amount'
      }, {
        title: '结算对象',
        dataIndex: 'custName',
        width: 210
      }
    ]

    const columns4 = [
      {
        title: '总应收',
        dataIndex: 'a'
      }, {
        title: '总应付',
        dataIndex: 'b'
      }, {
        title: '总毛利',
        dataIndex: 'c'
      }
    ]

    let validatecontainerNoAndName = (rule, value, callback) => {
      if (this.form.containerNo && this.form.containerNo.length > 15) {
        callback(new Error('箱号限制15长度'))
      } else {
        callback()
      }
    }

    const columnsLocal =
      [
        {
          title: '操作时间',
          dataIndex: 'createTime',
          width: 170,
          customRender: (text, record, index) => {
            if (index === 0) {
              return <div>{text}<span class='redMsg'>最新记录</span></div>
            }
            return text
          }
        },
        {
          title: '操作人',
          dataIndex: 'operator'
        },
        {
          title: '费用类型',
          dataIndex: 'feeName'
        },
        {
          title: '金额',
          dataIndex: 'cnyAmount'
        },
        {
          title: '结算对象',
          dataIndex: 'custName'
        },
        {
          title: '备注',
          width: 150,
          ellipsis: true,
          dataIndex: 'remark'
        }
      ]

    return {
      OrderOptions,
      sealNoAndNameDisplayId: '',
      sealNoAndNameList: [], // 箱号（持箱人）
      // 装卸详情
      form: {
        orderTruckId: '',
        requiredArriveTime: null,
        goodsWeight: '',
        containerNo: '',
        holderName: '',
        containerSealNo: '',
        dispatcherRemark: ''
      },
      detail: {
        orderType: ''
      },
      editpart: buttonDefault,
      rules: {
        custId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        name: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        requiredArriveTime: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        containerNoAndName: [{ validator: validatecontainerNoAndName, trigger: 'blur' }]
      },
      // 门点
      columns,
      loading: false,
      addressInfo: {
        opeType: '', // 操作类型：1装货，2卸货，3提箱
        addressType: '', // 门点类型：1港口，2门点
        portId: '', // 港口id
        province: '', // 省
        city: '', // 市
        area: '', // 区
        address: '', // 详细地址
        linkMan: '', // 联系人
        linkManPhone: '', // 联系人手机号
        remark: '' // 备注
      },
      tableData: [],
      // 封号modal
      sealNoVisible: false,
      containerSealNo: '', // 封号modal
      sealNoUpdateReason: '', // 封号modal
      // 门点modal
      loadingVisible: false,
      loadingGateData: null,

      // tab2
      truckFlowList: [],
      // modal
      flowVisible: false,
      flow: {},
      // tab3 1应收、2应付
      feeTypeList1: [],
      feeTypeList2: [],
      columns0,
      columns1,
      columns2,
      addVisible: false,
      currentAddType: '',
      feeForm: defaultFeeForm(1),
      tempRecord: {},
      feeList: [],
      custIdList: [],
      feeRules: {
        custId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        feetypeId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        amount: [{ required: true, message: fomrMessage, trigger: 'blur' }]
      },
      detailVisible: false,
      k1: 0.0,
      k2: 0,
      k3: 0.0,
      columns3,
      columns4,
      oilDetail: {
        totalAmount: '0.0',
        purchaseList: []
      },
      // 派
      assignModal: {
        type: 'ASSIGN', // 'ASSIGN', 'RE_ASSIGN', 'BATCH_ASSIGN'
        visible: false,
        order: {}
      },
      moneyTypeArray: [],
      // 1.1 新
      formSave: {
        a: '',
        b: ''
      },
      rulesSave: {
        a: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        b: [{ required: true, message: fomrMessage, trigger: 'blur' }]
      },
      clicked: false,
      // 历史记录
      historyVisible: false,
      columnsLocal,
      detailData: [],
      addConfirmLoading: false,
      disabledCust0: false,
      disabledCust: false
    }
  },
  computed: {
    showOilDetail () {
      return this.detail.singleOilConsumption && this.detail.doubleOilConsumption
    },
    statusStr () {
      // 待接单、待派单、司机待接单、司机待出发、运输中、已完成、已结算、已作废
      return statusArray[this.detail.status]
    },
    baseEditable () { // 已完成，已结算，已作废订单
      return this.detail.status !== 6 && this.detail.status !== 8 && this.detail.status !== 7
    },
    completedOrder () { // 仅已完成 可编辑 箱号封号 1.0紧急修改
      return this.detail.status === 6
    },
    requiredArriveTimeObj () {
      return this.form.requiredArriveTime ? moment(this.form.requiredArriveTime) : null
    },
    dispatchTypeStr () {
      return this.detail.dispatchType === 1 ? '提箱离港' : (this.detail.dispatchType === 2 ? '空车离港' : (this.detail.dispatchType === 3 ? '套箱接单' : '--'))
    },
    dispatchEmptyOrHeavyStr () {
      return this.detail.dispatchEmptyOrHeavy === 1 ? '空箱' : (this.detail.dispatchEmptyOrHeavy === 2 ? '重箱' : '--')
    },
    driverStr () {
      if (!this.detail.driverPhone && !this.detail.driverName) return '--'
      return `${this.detail.driverPhone} · ${this.detail.driverName}`
    },
    isLandCenterOrder () {
      return this.detail.belongCompany === 'JIA_TE'
    },
    isExportOrder () {
      return !!~this.detail.orderType.indexOf('_EXPORT')
    },
    isImportOrder () {
      return !!~this.detail.orderType.indexOf('_IMPORT')
    },
    currentAddTypeStr () {
      return this.currentAddType === 1 ? '收' : (this.currentAddType === 2 ? '付' : '')
    },
    data1 () {
      let a = 0
      this.feeTypeList1.forEach(v => {
        a += Math.round(v.amount * v.rate * 100) / 100
      })
      return Math.round(a * 100) / 100
    },
    data2 () {
      let a = 0
      this.feeTypeList2.forEach(v => {
        a += Math.round(v.amount * v.rate * 100) / 100
      })
      return Math.round(a * 100) / 100
    },
    billStatusStr () {
      return this.detail.isCostRecorded === 1 ? '费用已录完' : '费用未录完'
    },
    isOilOut () {
      return this.detail.isOilOut === 1
    }
  },
  methods: {
    onChangeTab (key) {
      if (key === '2') {
        this.initTruckFlowList()
      } else if (key === '3') {
        this.initOrderCostList()
        this.initDetail().then(oilVolume => {
          if (this.detail.tractorId && !this.isOilOut) {
            queryTruckOilInByOilVolume({ tractorId: this.detail.tractorId, oilVolume }).then(rsp => {
              this.oilDetail.purchaseList = rsp.data.oilInList
              this.oilDetail.totalAmount = rsp.data.totalAmount
            })
          }
        })
      } else if (key === '1') {
        this.initDetail()
      }
    },
    initDetail () {
      return new Promise(resolve => {
        queryTruckOrderDetail({ orderTruckId: this.id }).then(rsp => {
          this.detail = rsp.data
          this.k2 = rsp.data.rate
          this.tableData = rsp.data.addressList.map(v => ({
            isJiahuaOriPort: this.detail.belongCompany === 'JIA_HUA' && v.addressType === 1, // 佳华 港口 只能编辑类型
            ...v
          }))
          this.k1 = this.detail.mileage || 0.0
          this.k2 = this.detail.rate || 0.0
          this.k3 = this.detail.oilVolume || 0.0
          this.combineObjCommons(this.form, rsp.data)
          this.oilDetail.totalAmount = this.detail.totalAmount || 0.0
          resolve(this.k3)
        })
      })
    },
    orderTypeStr (key) {
      const t = this.OrderOptions.filter(v => v.key === key)[0]
      if (t) return t.title
      return ''
    },
    getSealNoAndNameString (containerNo, holderName) {
      let holderNameResult = holderName ? `(${holderName})` : ''
      return containerNo ? `${containerNo}${holderNameResult}` : ''
    },
    handleNameChange (nameLike = '') {
      // type箱态：1空，2重
      queryReportContainerListPc({
        word: nameLike
      }).then(rsp => {
        this.sealNoAndNameList = rsp.data
      })
    },
    handleNameSelect (key) {
      const t = this.sealNoAndNameList.filter(v => v.containerFlowId === key)[0]
      if (t) {
        queryContainerNoIsHaveOrder({
          containerNo: t.containerNo,
          orderTruckId: this.id
        }).then(rsp => {
          if (rsp.data.isPass === 1) {
            this.$message.warning('箱号已被其他订单使用！')
          }
          this.form.containerNo = t.containerNo
          this.form.holderName = t.holderName
        }).catch(() => {
          this.sealNoAndNameDisplayId = this.getSealNoAndNameString(this.detail.containerNo, this.detail.holderName)
          this.form.containerNo = ''
          this.form.holderName = ''
        })
      }
      this.handleNameChange()
    },
    onChangeDate (e, dataStr) {
      this.form.requiredArriveTime = dataStr
    },
    combineObjCommons (sm, big) {
      for (let k in sm) {
        sm[k] = big[k]
      }
    },
    changeA (e) {
      let x = e.target.value.toUpperCase()
      x = x.replace(/[^a-zA-Z0-9]/g, '')
      this.formSave.a = x
    },
    getOrderTruckOilVolume () {
      queryTruckOilInByOilVolume({ tractorId: this.detail.tractorId, oilVolume: this.k3 }).then(rsp => {
        this.oilDetail.purchaseList = rsp.data.oilInList
        this.oilDetail.totalAmount = rsp.data.totalAmount
        updateOrderTruckInfo({
          orderTruckId: this.id,
          mileage: this.k1,
          rate: this.k2,
          oilVolume: this.k3,
          totalAmount: rsp.data.totalAmount
        })
      })
    },
    saveOilData () {
      this.getOrderTruckOilVolume()
    },
    onChangeMileage () {
      this.k3 = Math.round(this.k2 * this.k1 * 100) / 100
    },
    onChangeRate () {
      this.k3 = Math.round(this.k2 * this.k1 * 100) / 100
      this.getOrderTruckOilVolume()
    },
    onChangeOilVolume () {
      if (this.k2) this.k1 = Math.floor(this.k3 / this.k2 * 100) / 100
      else this.k1 = 0
    },
    // modal - 修改封号以及原因
    changeContainerSealNo () {
      this.containerSealNo = this.form.containerSealNo
      this.sealNoUpdateReason = this.form.sealNoUpdateReason
      this.sealNoVisible = true
    },
    setSealNoData () {
      this.form.containerSealNo = this.containerSealNo
      this.form.sealNoUpdateReason = this.sealNoUpdateReason
      this.sealNoVisible = false
    },
    changeSealNoCancel () {
      this.sealNoVisible = false
    },
    saveFields (data) {
      this.form.type = 1
      return updateOrderTruckInfo(this.form).then(rsp => {
        this.detail = Object.assign({}, this.detail, this.form)
        this.$message.success('更新成功')
      })
    },
    editpartHandle (isCancel) {
      if (!this.$root._bc.editInfo) {
        this.$message.error('您无此权限！')
        return
      }
      this.cancelSave()
      if (!this['editpart'].flag) {
        if (isCancel) {
          this.$refs['form'].resetFields()
          this.combineObjCommons(this.form, this.detail) // 复原form
          this['editpart'] = buttonDefault
        } else {
          this.$refs['form'].validate(valid => {
            if (valid) {
              this.saveFields(this['form']).then(() => {
                this['editpart'] = buttonDefault
              })
            }
          })
        }
      } else {
        this['editpart'] = buttonEdit
        this.sealNoAndNameDisplayId = this.getSealNoAndNameString(this.detail.containerNo, this.detail.holderName)
      }
    },
    // 门点信息
    loadingGate () {
      if (!this.$root._bc.editAddress) {
        this.$message.error('您无此权限！')
        return
      }
      this.loadingGateData = { orderTruckId: this.id }
      this.loadingVisible = true
    },
    loadingClose (data) {
      if (data) {
        this.initDetail()
      }
      this.loadingVisible = false
    },
    editIt (index) {
      if (!this.$root._bc.editAddress) {
        this.$message.error('您无此权限！')
        return
      }
      this.loadingGateData = this.tableData[index]
      this.loadingVisible = true
    },
    deleteIt (index) {
      if (!this.$root._bc.editAddress) {
        this.$message.error('您无此权限！')
        return
      }
      this.loading = true
      deleteOrderTruckAddress({ addressId: this.tableData[index].addressId }).then(rsp => {
        this.$message.success('删除成功')
        this.tableData.splice(index, 1)
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    // 订单流转 tab
    initTruckFlowList () {
      queryOrderTruckFlowList({ orderTruckId: this.id }).then(rsp => {
        this.truckFlowList = rsp.data
      })
    },
    openFlowDetail (v) {
      this.flow = {
        id: v.flowId,
        type: v.type,
        isLandCenterOrder: this.isLandCenterOrder,
        isImportOrder: this.isImportOrder,
        baseEditable: this.baseEditable
      }
      this.flowVisible = true
    },
    dealFlowModal () {
      this.flowVisible = false
    },
    // 费用信息
    initOrderCostList () {
      queryShipOrderCostList({
        id: this.id,
        businessType: 'JIA_TE'
      }).then(rsp => {
        this.feeTypeList1 = rsp.data.filter(v => v.feeType === 1)
        this.feeTypeList2 = rsp.data.filter(v => v.feeType === 2)
      })
    },
    // fee modal
    initFeeTypeRequest (e) {
      queryFeeTypeList(e)
        .then(res => {
          this.feeList = res.data.filter(v => !(!this.isLandCenterOrder && (v.name === '应收客户' || v.name === '应付客户')))

          if (this.feeForm && this.feeForm.feetypeId) {
            this.moneyTypeArray = res.data.filter(v => v.id === this.feeForm.feetypeId)[0].currencyType.split(',')
          }
        })
        .catch(rs => { })
    },
    onchangeFeeType (id) {
      const t = this.feeList.filter(v => v.id === id)[0]
      this.disabledCust = false

      if (t) {
        if (this.isLandCenterOrder && (t.name === '应收客户' || t.name === '应付客户')) {
          this.feeForm.custId = this.detail.custId
          this.disabledCust = true
        } else {
          this.feeForm.custId = ''
        }
        this.moneyTypeArray = t.currencyType.split(',')
        this.feeForm.currencyType = this.moneyTypeArray[0]
      } else {
        this.moneyTypeArray = []
        this.feeForm.currencyType = ''
      }
    },
    addFee (type) {
      if (type === 1 && !this.$root._bc.addReceivable) {
        this.$message.error('您无此权限！')
        return
      }
      if (type === 2 && !this.$root._bc.addPay) {
        this.$message.error('您无此权限！')
        return
      }
      this.moneyTypeArray = []
      this.feeForm = defaultFeeForm(type)
      this.currentAddType = type // 1应收、2应付
      this.disabledCust = false
      this.disabledCust0 = false
      this.handleCustNameChange()
      this.initFeeTypeRequest({
        status: 1,
        belongCompany: 'JIA_TE',
        feeType: type
      })
      this.addVisible = true
    },
    editbill (record, type) {
      // editCost
      if (type === 1) {
        if (!this.$root._bc.editReceivable) {
          this.$message.error('您无此权限！')
          return false
        }
      } else if (type === 2) {
        if (!this.$root._bc.editPay) {
          this.$message.error('您无此权限！')
          return false
        }
      }

      this.moneyTypeArray = []
      this.feeForm = { ...record }
      this.tempRecord = { ...record }
      this.feeForm.feetypeId = record.feeTypeId // 字段名不一致，需要赋值
      this.tempRecord.feetypeId = record.feeTypeId

      this.disabledCust = false
      this.disabledCust0 = false
      if (this.isLandCenterOrder && (record.feeName === '应收客户' || record.feeName === '应付客户')) {
        this.disabledCust = true
        this.disabledCust0 = true
      }

      this.currentAddType = record.feeType // 1应收、2应付
      this.moneyTypeArray = record.currencyType.split(',')
      this.handleCustNameChange()
      this.initFeeTypeRequest({
        status: 1,
        belongCompany: 'JIA_TE',
        feeType: record.feeType
      })
      this.addVisible = true
    },
    handleCustNameChange (nameLike = '') {
      queryCustNameList({
        nameLike,
        belongCompany: 'JIA_TE',
        custTypeLike: 'SUPPLIER',
        status: 1,
        isReceivable: this.currentAddType === 1 ? 1 : '',
        isPayable: this.currentAddType === 2 ? 1 : ''
      }).then(rsp => {
        this.custIdList = rsp.data.filter(v => !~v.name.indexOf('佳华'))
      })
    },
    emptyChange () {
      this.handleCustNameChange()
    },
    saveAddFee () {
      this.$refs.feeForm.validate(valid => {
        if (valid) {
          this.addConfirmLoading = true
          if (!this.feeForm.id) {
            addBillCost({ ...this.feeForm, businessId: this.id }).then(rsp => {
              this.$message.success('保存成功')
              this.addVisible = false
              this.initOrderCostList()
              setTimeout(() => { this.addConfirmLoading = false }, 1000)
            }).catch(() => { this.addConfirmLoading = false })
          } else {
            if (this.tempRecord.custId !== this.feeForm.custId || this.tempRecord.feetypeId !== this.feeForm.feetypeId || this.tempRecord.amount !== this.feeForm.amount ||
              this.tempRecord.currencyType !== this.feeForm.currencyType || this.tempRecord.remark !== this.feeForm.remark) {
              updateBillCost(this.feeForm).then(rsp => {
                this.$message.success('更新成功')
                this.tempRecord = {}
                this.addVisible = false
                this.initOrderCostList()
                setTimeout(() => { this.addConfirmLoading = false }, 1000)
              }).catch(() => { this.addConfirmLoading = false })
            } else {
              this.$message.error('内容没有变更，无法保存！')
              this.addConfirmLoading = false
            }
          }
        }
      })
    },
    cancelAddFee () {
      this.tempRecord = {}
      this.addVisible = false
    },
    sureOil () {
      if (!this.$root._bc.editCost) {
        this.$message.error('您无此权限！')
        return
      }
      // 是否确定油耗费用，确定之后不可进行更改！
      const _this = this
      this.$confirm({
        title: '是否确定油耗费用，确定之后不可进行更改！',
        onOk () {
          updateOrderTruckOilVolumeNew({ orderTruckId: _this.id, mileage: _this.k1, rate: _this.k2, oilVolume: _this.k3 }).then(rsp => {
            _this.$message.success('油耗费用更新成功')
            _this.detail.isOilOut = 1

            queryOrderTruckOilDetail({ orderTruckId: _this.id }).then(rsp => {
              if (rsp.data && rsp.data[0]) {
                _this.oilDetail.purchaseList = rsp.data
              }
            })

            _this.initDetail()
          })
        }
      })
    },
    viewDetail () {
      this.oilDetail.purchaseList = []
      queryOrderTruckOilDetail({ orderTruckId: this.id }).then(rsp => {
        if (rsp.data && rsp.data[0]) {
          this.oilDetail.purchaseList = rsp.data
        }
      })
      this.detailVisible = true
    },
    viewDetailLocal () {
      this.detailVisible = true
    },
    cancelDetail () {
      this.detailVisible = false
    },
    // 指派/改派/批量
    doAssign (type, status, orderTruckIds, dispatchType = 1, dispatchEmptyOrHeavy = 1) {
      if (!this.$root._bc.dispatch) {
        this.$message.error('您无此权限！')
        return
      }
      this.assignModal.type = type
      this.assignModal.order = {
        status,
        orderTruckIds,
        dispatchType,
        dispatchEmptyOrHeavy
      }
      this.assignModal.visible = true
    },
    setAssignVisible (v) {
      if (v) { // 保存成功
        this.initDetail()
      }
      this.assignModal.visible = false
    },
    openSave () {
      this.clicked = true
    },
    cancelSave () {
      this.clicked = false
      this.formSave = { a: '', b: '' }
      if (this.$refs.formSave) this.$refs.formSave.resetFields()
    },
    save () {
      this.$refs.formSave.validate(valid => {
        if (valid) {
          queryContainerNoIsHaveOrder({
            containerNo: this.formSave.a,
            orderTruckId: this.id
          }).then(rsp => {
            if (rsp.data.isPass === 1) {
              this.$message.warning('箱号已被其他订单使用！')
            } else {
              this.form.containerNo = this.formSave.a
              this.form.holderName = this.formSave.b
              this.sealNoAndNameDisplayId = `${this.formSave.a}(${this.formSave.b})`
              this.cancelSave()
            }
          })
        }
      })
    },
    handleMenuClick (e) {
      if (e.key === 1 && this.detail.isCostRecorded !== 1) {
        if (!this.$root._bc.editCostRecorded) {
          this.$message.error('您无此权限！')
          return
        }
        updateOrderTruckCostRecorded({ orderTruckId: this.id, isCostRecorded: e.key }).then(rsp => {
          this.detail.isCostRecorded = e.key
          this.$message.success('费用状态更新成功')
        })
      } else if (e.key === 0 && this.detail.isCostRecorded !== 0) {
        if (!this.$root._bc.editCostRecorded) {
          this.$message.error('您无此权限！')
          return
        }
        updateOrderTruckCostRecorded({ orderTruckId: this.id, isCostRecorded: 0 }).then(rsp => {
          this.detail.isCostRecorded = 0
          this.$message.success('费用状态更新成功')
        })
      }
    },
    viewHistory (id) {
      queryHistoryCostList({ id }).then(rsp => {
        this.detailData = rsp.data
      })
      this.historyVisible = true
    },
    cancelSee () {
      this.historyVisible = false
      this.detailData = []
    }
  },
  mounted () {
    this.initDetail()
    this.handleNameChange()
  },
  watch: {
    sealNoAndNameDisplayId (newd) {
      if (!newd) {
        this.form.containerNo = ''
        this.form.holderName = ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ td {
  position: relative;
  .redMsg {
    position: absolute;
    display: inline-block;
    background: red;
    top: 0;
    width: 60px;
    left: 0;
    font-size: 12px;
    height: 16px;
    text-align: center;
    color: white;
  }
}
.page-header {
  background: #fff;
  padding: 12px 24px;
  .breadcrumb {
    margin-bottom: 16px;
  }

  .detail {
    display: flex;

    .main {
      width: 100%;
      flex: 0 1 auto;

      .row {
        display: flex;
        width: 100%;
      }

      .title {
        font-size: 20px;
        font-weight: 500;
        line-height: 28px;
        color: rgba(0, 0, 0, 0.85);
        flex: auto;
        h1 {
          color: rgba(0, 0, 0, 0.85);
          font-weight: 600;
          font-size: 20px;
        }
      }
      .logo {
        width: 28px;
        height: 28px;
        border-radius: 4px;
        margin-right: 10px;
      }
      .content,
      .headerContent {
        flex: auto;
        color: rgba(0, 0, 0, 0.45);
        line-height: 22px;

        .link {
          margin-top: 16px;
          line-height: 24px;

          a {
            font-size: 14px;
            margin-right: 32px;
          }
        }
      }
      .extra {
        flex: 0 1 auto;
        margin-left: 88px;
        min-width: 242px;
        text-align: right;
      }
      .action {
        margin-left: 56px;
        min-width: 266px;
        flex: 0 1 auto;
        text-align: right;
        &:empty {
          display: none;
        }
      }
      .page-menu-tabs {
        width: 100%;
        margin: 15px 0 -17px 8px;
      }
    }
  }
}
.ant-card {
  position: relative;
  margin: 0 24px 24px 24px;
  border: none;
  .cardEdit {
    position: absolute;
    right: 24px;
    top: 24px;
    z-index: 2;
  }
  .cardCancel {
    position: absolute;
    right: 104px;
    top: 24px;
    z-index: 2;
  }
  .card-title {
    position: relative;
    padding-left: 16px;
    font-size: 18px;
    line-height: 1;
    color: #000;
    margin-bottom: 20px;
    &:before {
      content: '';
      width: 5px;
      height: 18px;
      background: #1890ff;
      border-radius: 4px;
      position: absolute;
      left: 0;
      top: -1px;
    }
  }
  .hasContent {
    margin-bottom: 20px;
  }
}

.detail-layout {
  margin-left: 38px;
}
.text {
  color: rgba(0, 0, 0, 0.45);
}

.heading {
  color: rgba(0, 0, 0, 0.85);
  font-size: 20px;
}

.no-data {
  color: rgba(0, 0, 0, 0.25);
  text-align: center;
  line-height: 64px;
  font-size: 16px;

  i {
    font-size: 24px;
    margin-right: 16px;
    position: relative;
    top: 3px;
  }
}

.ant-form-inline .ant-form-item-with-help {
  margin-bottom: 5px !important;
}

.detail1 {
  padding-top: 10px;
  span.formText {
    line-height: 25px;
    display: inline-block;
    padding-top: 7px;
  }
  /deep/ .ant-form-item {
    margin: 0;
  }

  .inputReadonly {
    outline: none;
    cursor: pointer;
    box-sizing: border-box;
    margin: 0px;
    margin-right: 5px;
    padding: 0;
    font-variant: tabular-nums;
    list-style: none;
    font-feature-settings: 'tnum';
    position: relative;
    display: inline-block;
    width: 90%;
    height: 32px;
    padding: 4px 11px;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    line-height: 1.5;
    background-color: #fff;
    background-image: none;
    border: 1px solid #d9d9d9 !important;
    border-radius: 4px;
    transition: all 0.3s;
    &:hover {
      border-color: #1890ff;
    }
  }
}

.leftFlowList {
  width: 100%;
  overflow: auto;
  padding: 20px 5px;
  max-height: 640px;
  .errorClass {
    background: #ffeeee;
  }
}

.selfFlag {
  display: inline-block;
  border: 1px solid #1890ff;
  color: #1890ff;
  line-height: 12px;
  font-size: 12px;
  padding: 0 3px;
  margin-left: 8px;
  border-radius: 4px;
}

.mapLoc {
  border: 1px solid #f2f2f2;
  padding: 5px;
  margin: 20px 1% 20px 2%;
  width: 98%;
}
</style>
<style lang="less">
.title .ant-form-item-label label {
  font-size: 20px;
  font-weight: 600;
}
.ant-tabs-bar {
  padding: 0 24px;
  background: #fff;
  margin: 0 0 24px 0;
  border-bottom: 0;
}
.ant-tabs-nav .ant-tabs-tab {
  font-size: 16px;
}
.orange {
  color: orange;
}
</style>
